#include "homepage.h"
#include "ui_homepage.h"
#include <QDebug>
#include <QMessageBox>

HomePage::HomePage(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::HomePage)
{
    ui->setupUi(this);

    // 线程初始化
    m_dc = new DataController;
    m_dcThread = new QThread(this);
    m_dc->moveToThread(m_dcThread);
    m_dcThread->start();

    // 注册数据库连接信号，保证子线程负责连接数据库
    connect(this, &HomePage::initSql, m_dc, &DataController::initDBconnection);
    // 接受从子线程传回的连接状态信号
    connect(m_dc, &DataController::connectionState, this, &HomePage::dealConnectionState);
    // 注册获取所有表名称信号
    connect(this, &HomePage::getTableName, m_dc, &DataController::getTableNamesFromDB);
    // 接受子线程传来的所有表名称
    connect(m_dc, &DataController::returnTableNameList, this, &HomePage::showTableNames);
    // 根据用户选择切换数据表
    connect(ui->chooseTable, &QComboBox::currentTextChanged, m_dc, &DataController::switchTable);
}

HomePage::~HomePage()
{
    // 子线程安全退出
    m_dcThread->quit();
    m_dcThread->wait();
    delete ui;
}


void HomePage::on_checkScore_clicked()
{
    this->hide();

    // 展示窗口初始化
    ss = new ScoreShow(m_dc);
    connect(ss, &ScoreShow::showHomePage, this, [=](){
        this->show();
        ss->deleteLater();
    });
    ss->show();
    qDebug() << "展示完毕";

}


void HomePage::on_connectBtn_clicked()
{
    emit initSql(ui->userLine->text(), ui->pswLine->text());

}

void HomePage::dealConnectionState(bool ok)
{
    if (!ok)
    {
        QMessageBox::information(this, "连接失败", "请重新连接");
        //        qDebug() << "failed";
        return;
    }
    //        qDebug() << "ok";

    QMessageBox::information(this, "连接成功", "请选择数据表");
    emit getTableName();
}

void HomePage::showTableNames(const QVector<QString> tableNameList)
{
    ui->chooseTable->clear();
    for (QString tableName: tableNameList)
    {
//        qDebug() << tableName;
        ui->chooseTable->addItem(tableName);
    }
}

